﻿using System;

namespace MultiViewer.Network
{
    public delegate object MessageHandler<T>(T message);
    public delegate void AsyncMessageHandler<T>(T message, HandlerResult<object> result);
    
    public delegate void NotificationHandler<T>(T notification);

    public delegate TState PrepareHandler<TRequest, TState>(TRequest request) 
        where TRequest : Message 
        where TState : TransactionState<TRequest>;
    public delegate void AsyncPrepareHandler<TRequest, TState>(TRequest request, HandlerResult<TState> result) 
        where TRequest : Message
        where TState : TransactionState<TRequest>;
    public delegate void CommitRollbackHandler<TState>(TState state);

    internal class TransactionHandler
    {
        private Delegate prepare;
        private Delegate commit;
        private Delegate rollback;

        public TransactionHandler(Delegate prepare, Delegate commit, Delegate rollback)
        {
            this.prepare = prepare;
            this.commit = commit;
            this.rollback = rollback;
        }

        public ITransactionState Prepare(object request) 
        {
            return (ITransactionState)prepare.DynamicInvoke(request);
        }

        public void Commit(object state)
        {
            commit.DynamicInvoke(state);
        }

        public void Rollback(object state)
        {
            rollback.DynamicInvoke(state);
        }
    }

    public delegate void NodeConnectionHandler(int nodeId);
}